import BaseComponent from '../../prototype/BaseComponent.js'
import UserModel from '../../models/UserModel.js'
import formidable from 'formidable'

class User extends BaseComponent {
	constructor() {
		super();
		this.queryUserList = this.queryUserList.bind(this);
		this.getUserItemById = this.getUserItemById.bind(this);
		this.addUserItem = this.addUserItem.bind(this);
		this.editUserItem = this.editUserItem.bind(this);
		this.delUserItem = this.delUserItem.bind(this);
		this.loginIn = this.loginIn.bind(this);
		this.loginOut = this.loginOut.bind(this);
	}
	async queryUserList(req, res, next){
		const params = {
			primaryId: req.query.primaryId,
			userId: req.query.userId,
			userName: req.query.userName,
			nickName: req.query.nickName,
			sex: req.query.sex,
			password: req.query.password,
		};

		let result = await UserModel.queryUserList(params);
		res.send(this.oklist(result));
	}
	async getUserItemById(req, res, next) {
		const params = {
			primaryId: req.query.primaryId,
		};
		let result = await UserModel.getUserItemById(params);
		res.send(this.okdata(result));
	}
	async addUserItem(req, res, next) {
		const form = new formidable.IncomingForm();
		form.parse(req, async (err, fields, files) => {
			const params = {
				primaryId: Date.now(),
				userId: fields.userId,
				userName: fields.userName,
				nickName: fields.nickName,
				sex: fields.sex,
				password: fields.password,
			};
			let result = await UserModel.addUserItem(params);
			res.send(this.ok(result));
		});
	}
	async editUserItem(req, res, next) {
		const form = new formidable.IncomingForm();
		form.parse(req, async (err, fields, files) => {
			const params = {
				primaryId: fields.primaryId,
				userId: fields.userId,
				userName: fields.userName,
				nickName: fields.nickName,
				sex: fields.sex,
				password: fields.password,
			};
			let result = await UserModel.editUserItem(params);
			res.send(this.ok(result));
		});
	}
	async delUserItem(req, res, next) {
		const params = {
			primaryId: req.query.primaryId,
		};
		let result = await UserModel.delUserItem(params);
		res.send(this.ok());
	}
	async loginIn(req, res, next) {
		const form = new formidable.IncomingForm();
		form.parse(req, async (err, fields, files) => {
			const params = {
				userId: fields.userId,
				password: fields.password,
			};
			let result = await UserModel.loginIn(params);

			if(req.session) {
				let userId = fields.userId;
				req.session.userId = userId;
				res.cookie("userId", userId, {maxAge: 900000, httpOnly: true});
				console.log('session.userId', req.session.userId)
			}
			res.send(this.ok());
		});
	}
	loginOut(req, res, next) {
		if(req.session) {
			req.session.userId = null;
		}
		res.send(this.ok());
	}
}
export default new User();